<template>
	<div class="collapse">
		<el-button @click="openEventDialog" type="primary" size="small">事件配置</el-button>
		<!-- 事件配置 -->
		<el-dialog
			title="事件配置"
			custom-class="event-config-dialog"
			:close-on-click-modal="true"
			:fullscreen="true"
			width="100%"
			:visible.sync="eventDialog.visible"
			append-to-body
		>
			<avue-crud :data="eventDialog.data" :option="eventDialog.option" @row-save="rowSave" @row-update="rowUpdate" @row-del="rowDel">
				<!-- <template slot-scope="{ row }" slot="args">
                    <monaco-editor
                        v-model="row.args"
                        :height="100"
                        language="javascript"
                    ></monaco-editor>
                </template> -->
				<template slot="eventType" slot-scope="{ row }">
					<el-tag v-if="row.eventType == 1" type="success">控制显隐</el-tag>
					<el-tag v-if="row.eventType == 2" type="info">打开链接</el-tag>
					<el-tag v-if="row.eventType == 3">触发回调</el-tag>
					<el-tag type="danger" v-if="row.eventType == 4">自定义函数</el-tag>
				</template>

				<template slot="status" slot-scope="{ row }">
					<el-switch v-model="row.status" active-text="启用" inactive-text="关闭" :active-value="1" :inactive-value="0"> </el-switch>
				</template>

				<template slot="args" slot-scope="{ row }">
					<el-input type="textarea" disabled :autosize="{ minRows: 2, maxRows: 4 }" v-model="row.args"> </el-input>
				</template>

				<template slot-scope="{ row, index }" slot="menu">
					<el-button type="text" icon="el-icon-edit" size="small" @click="openCustomSendParamsDialog(row, index)">自定义参数</el-button>
				</template>
			</avue-crud>
			<span slot="footer" class="dialog-footer">
				<el-button size="small" type="primary" icon="el-icon-refresh" @click="saveEventConfig">保存</el-button>
			</span>
		</el-dialog>

		<!-- 自定义参数配置 -->
		<el-dialog
			title="自定义发送参数配置"
			custom-class="custom-param-config-dialog"
			:close-on-click-modal="true"
			:fullscreen="false"
			width="50%"
			:visible.sync="customSendParamsDialog.visible"
			append-to-body
		>
			<monaco-editor v-model="customSendParamsDialog.code" :height="400" language="javascript"></monaco-editor>
			<span slot="footer" class="dialog-footer">
				<el-button size="small" type="primary" icon="el-icon-refresh" @click="saveCustomSendParams">保存</el-button>
			</span>
		</el-dialog>
	</div>
</template>
<script>
import { mapState } from 'vuex';
import { funEval, uuid, getFunction, getJson } from '@/utils/utils';
import { tableEventOption, dicOption, tableAlarmOption } from '@/option/config';
import MonacoEditor from '@/page/components/editor';
export default {
	components: { MonacoEditor },
	props: {
		activeObj: {
			type: Object,
			default: () => {}
		},
		childList: {},
		dataSource: {}
	},
	data() {
		return {
			rowIndex: -1,
			tableEventOption: tableEventOption,
			childProps: {
				label: 'name',
				value: 'index'
			},
			eventDialog: {
				visible: false,
				data: [],
				option: {
					align: 'center',
					height: 700,
					menuAlign: 'center',
					menuWidth: 250,
					refreshBtn: false,
					columnBtn: false,
					labelWidth: 100,
					index: true,
					column: [
						{
							label: '事件Id',
							prop: 'eventId',
							disabled: true,
							addDisplay: false,
							editDisplay: false,
							hide: true
						},
						{
							label: '事件名称',
							prop: 'eventName',
							type: 'select',
							dicData: [],
							width: 200,
							rules: [
								{
									required: true,
									message: '请选择事件名称',
									trigger: 'change'
								}
							]
						},
						{
							label: '事件类型',
							prop: 'eventType',
							type: 'select',
							width: 100,
							slot: true,
							value: '3',
							dicData: [
								{ label: '控制显隐', value: '1' },
								{ label: '打开链接', value: '2' },
								{ label: '触发回调', value: '3' },
								{ label: '自定义函数', value: '4' }
							],
							rules: [
								{
									required: true,
									message: '请选择事件类型',
									trigger: 'change'
								}
							],
							control: (val, form) => {
								return {
									linkUrl: {
										display: val == 2
									},
									customFn: {
										display: val == 4
									}
								};
							}
						},
						{
							label: '链接地址',
							prop: 'linkUrl',
							width: 200,
							display: false,
							hide: true,
							rules: [
								{
									required: false,
									message: '请输入链接地址',
									trigger: 'change'
								}
							]
						},
						{
							label: '自定义函数',
							prop: 'customFn',
							width: 200,
							display: false,
							hide: true,
							rules: [
								{
									required: false,
									message: '请输入自定义函数',
									trigger: 'change'
								}
							]
						},
						{
							label: '接收组件',
							prop: 'targetCompId',
							overHidden: true,
							type: 'select',
							dicData: [],
							width: 400,
							filterable: true,
							rules: [
								{
									required: true,
									message: '请选择接收组件',
									trigger: 'change'
								}
							]
						},
						{
							label: '状态',
							prop: 'status',
							type: 'switch',
							width: 150,
							value: 1,
							dicData: [
								{
									label: '关闭',
									value: 0
								},
								{
									label: '启用',
									value: 1
								}
							]
						},
						{
							label: '发送参数',
							prop: 'args',
							type: 'textarea',
							addDisplay: false,
							editDisplay: false,
							span: 24
						}
					]
				}
			},
			customSendParamsDialog: {
				visible: false,
				code: `(data)=>{
    return {}
}`
			}
		};
	},
	computed: {
		...mapState({
			globalEventList: state => state.event.globalEventList
		}),
		// 事件名称列表
		eventNameList() {
			return this.activeObj.eventNames.map(event => {
				return {
					value: event,
					label: event
				};
			});
		}
	},
	watch: {
		// activeObj: {
		//     handler(val) {
		//         if (this.activeObj.sql && this.isSql) {
		//             let mode = JSON.parse(crypto.decrypt(this.activeObj.sql));
		//             this.db = mode.id;
		//             this.sql = mode.sql;
		//         } else {
		//             this.db = "";
		//             this.sql = "";
		//         }
		//     },
		//     deep: true
		// }
	},
	methods: {
		// 函数类型切换
		fnTypeChange(value, item) {
			item.fnName = '';
			if (value == 2) {
				item.mutexTrigger = false;
			}
		},
		// 删除接收组件和组件函数
		deleteReceiveComp(item, cItem, cIndex) {
			item.receiveData.splice(cIndex, 1);
		},
		// 新增接收组件和组件函数
		addReceiveComp(item) {
			item.receiveData.push({
				compId: '',
				fnName: '',
				fnType: '1'
			});
		},
		// 新增字段
		addEventTable(item) {
			item.eventParams.push({
				field: '',
				bindValue: '',
				desc: '',
				fieldDisabled: false
			});
			this.mountCompEvent(item);
		},
		// 删除字段
		handleDelete(index, item) {
			item.eventParams.splice(index, 1);
			this.mountCompEvent(item);
		},
		// 图标折叠
		eventToggleIcon(item) {
			if (!item.open) {
				this.$set(item, 'open', true);
			} else {
				item.open = !item.open;
			}
		},
		// change接收组件
		changeReceiveCompIds(value, item) {
			this.mountCompEvent(item);
		},
		startEvent(item) {
			let compId = this.activeObj.index;
			item.compId = compId;
			this.mountCompEvent(item);
		},
		blurBindValue(item) {
			this.mountCompEvent(item);
		},
		mountCompEvent(item) {
			if (item.start) {
				// 注册组件事件
				this.$store.commit('event/registerEvent', item);
			} else {
				// 卸载组件事件
				this.$store.commit('event/unloadEvent', item);
			}
		},
		openEventDialog() {
			this.eventDialog.visible = true;
			this.eventDialog.data = this.deepClone(this.activeObj.eventConfig);
			let propEventNameIndex = this.eventDialog.option.column.findIndex(column => column.prop == 'eventName');
			if (propEventNameIndex > -1) {
				this.eventDialog.option.column[propEventNameIndex].dicData = this.eventNameList;
			}

			let propTargetCompIdIndex = this.eventDialog.option.column.findIndex(column => column.prop == 'targetCompId');
			if (propTargetCompIdIndex > -1) {
				this.eventDialog.option.column[propTargetCompIdIndex].dicData = this.childList.map(child => {
					return {
						label: child.name + '(' + child.index + ')',
						value: child.index
					};
				});
			}
		},
		rowSave(form, done, loading) {
			if (form.targetCompId) {
				form.eventId = form.targetCompId.substr(0, 3) + '-' + form.eventType + '-' + uuid();
			}
			form.args = JSON.stringify({}, null, 2);
			this.eventDialog.data.push(this.deepClone(form));
			done(form);
			// this.mountCompEvent(row);
			// done();
		},
		rowUpdate(form, index, done, loading) {
			if (form.targetCompId) {
				form.eventId = form.targetCompId.substr(0, 3) + '-' + form.eventType + '-' + uuid();
			}
			this.eventDialog.data.splice(index, 1, this.deepClone(form));
			done(form);
		},
		rowDel(form, index) {
			this.$confirm('此操作将永久删除该事件, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					this.eventDialog.data.splice(index, 1);
					this.$message({
						type: 'success',
						message: '删除成功!'
					});
				})
				.catch(() => {});
		},
		openCustomSendParamsDialog(row, index) {
			this.rowIndex = index;
			this.customSendParamsDialog.code = `(data)=>{
    return ${row.args}
}`;
			this.customSendParamsDialog.visible = true;
		},
		saveCustomSendParams() {
			let code = getFunction(this.customSendParamsDialog.code)(getJson(this.dataSource));
			this.$set(this.eventDialog.data[this.rowIndex], 'args', JSON.stringify(code, null, 2));
			// this.eventDialog.data[this.rowIndex].args =
			//     JSON.stringify(code);
			this.customSendParamsDialog.visible = false;
		},
		saveEventConfig() {
			// VUEX 处理事件池
			this.eventDialog.data.forEach(event => {
				event.compId = this.activeObj.index;
			});
			this.newMountCompEvent(this.eventDialog.data);
			let eventData = this.deepClone(this.eventDialog.data);
			this.activeObj.eventConfig = eventData.map(event => {
				return {
					compId: event.compId,
					eventId: event.eventId,
					eventName: event.eventName,
					eventType: event.eventType,
					status: event.status,
					linkUrl: event.linkUrl,
					customFn: event.customFn,
					args: event.args,
					targetCompId: event.targetCompId
				};
			});
			this.eventDialog.visible = false;
		},
		newMountCompEvent(data) {
			let unloadEventList = data.filter(d => d.status == 0);
			let regloadEventList = data.filter(d => d.status == 1);
			this.$store.commit('event/registerEvent', regloadEventList); // 注册组件事件
			this.$store.commit('event/unloadEvent', unloadEventList); // 卸载组件事件
		}
	}
};
</script>
<style lang="scss" scoped>
.collapse {
	padding: 10px;
	.collapse-item {
		margin-bottom: 10px;
		.event-start {
			display: flex;
			align-items: center;
			.event-title {
				flex: 1;
			}
			.icon {
				cursor: pointer;
				transform: rotate(0deg);
				transition: all 0.3s;
				&.arrow-bottom {
					transform: rotate(90deg);
					transition: all 0.3s;
				}
			}
		}
	}
}
.event-item-container {
	display: none;
	padding: 10px 0;

	&.isCollapse {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		transition: all 0.3s;
	}
	.addField {
		margin-top: 10px;
	}
}
.fnDeletcIcon {
	height: 28px;
	vertical-align: bottom;
}

.event-config-dialog {
	margin-top: 0vh !important;
	.el-dialog__body {
		padding: 0;
		.el-form-item--small {
			margin-bottom: 10px !important;
		}
		.data-config-item-value {
			.el-form-item__content {
				display: flex;
				button {
					margin-right: 10px;
				}
			}
		}
	}
	.inline-row {
		width: 50%;
		display: inline-block;
	}
}
</style>
